package com.example.microinvestuser.service.admin.impl;
import com.example.microinvestcommon.pojo.Result;
import com.example.microinvestcommon.util.JwtUtil;
import com.example.microinvestcommon.util.SHA256Util;
import com.example.microinvestcommon.vo.BuyStockVo;
import com.example.microinvestcommon.vo.SellStockVo;
import com.example.microinvestcommon.vo.UsersVo;
import com.example.microinvestuser.service.admin.AdminService;
import com.example.microinvestuser.dao.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class AdminServiceImpl implements AdminService {

    private final AdminMapper adminMapper;

    @Autowired
    public AdminServiceImpl(AdminMapper adminMapper){
        this.adminMapper=adminMapper;
    }


    @Override
    public Result<String> loginWithAdminNamePasswordService(String adminName, String password) {
        // 检查用户是否存在
        boolean AdminExists = adminMapper.existsByAdminName(adminName);
        if (!AdminExists) {
            return Result.error("用户不存在");
        }
        // 比对加密后的密码的哈希值
        String encryptedPassword = SHA256Util.getSHA256String(password);

        boolean passwordCorrect = adminMapper.comparePassword(adminName, encryptedPassword);
        if (!passwordCorrect) {
            return Result.error("用户名或密码错误");
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put("adminName",adminName);
        String token;
        try {
            token= JwtUtil.genToken(claims);
        } catch (Exception e) {
         return Result.error("token生成失败");
        }
        return Result.success(token);
    }

    @Override
    public Result<List<UsersVo>> getUsersMessageService(){
        //返回用户所有信息（列表形式）
        return Result.success(adminMapper.getUsersMessage());

    }

    @Override
    public Result<List<BuyStockVo>> getBuyStockMessage(){
        //返回所有股票买入信息（列表形式）
        return Result.success(adminMapper.getBuyStockMessage());

    }

    @Override
    public Result<List<SellStockVo>> getSellStockMessage(){
        //返回所有股票卖出信息（列表形式）
        return Result.success(adminMapper.getSellStockMessage());

    }

    @Override
    public Result<String> deleteStockMessage(List<String> stockSymbols) {
        try {
            for (String symbol : stockSymbols) {
                adminMapper.deleteStockMessage(symbol);
            }
        } catch (Exception e) {
           return Result.error("删除失败"+e);
        }
        return Result.success("删除成功");
    }
}
